import {StyleSheet, Text, TouchableOpacity, View, Image, Linking, ImageBackground} from 'react-native'
import React, {useEffect, useState} from 'react'
import PageScrollView from "@/components/PageScrollView";
import useGetStorage from "@/hooks/useGetStorage";
import LinearGradientText from "@/components/LinearGradientText";
import FcModal from '@/components/FcModal';
import FcButton from "@/components/FcButton";
import NoData from "@/components/NoData";
import {formatTimestamp} from "@/utils";
import {LinearGradient} from "expo-linear-gradient";
import {router} from "expo-router";
import {Flex} from "@ant-design/react-native";
import {useSelector} from "react-redux";

import {
  useGetProductUsageCountMutation,
  useGetUnreadQuantityMutation,
  useGetDeliveryPersonMutation,
  useLogoutMutation
} from "@/store/api/my/myApi";

type Props = {}

const my = (props: Props) => {
  const [userInfo, setUserInfo] = useState<any>({})
  const [productList, setProductList] = useState<any>([])
  const [productUsageData, setProductUsageData] = useState<any>({})
  const [newVersionOpen, setNewVersionOpen] = useState(false)
  const [unreadCount, setUnreadCount] = useState(0)
  const [deliveryPerson, setDeliveryPerson] = useState<any>({})
  const [deliveryPersonOpen, setDeliveryPersonOpen] = useState(false)
  const [exitOpen, setExitOpen] = useState(false)
  
  const [getProductUsageCountFun] = useGetProductUsageCountMutation()
  const [getUnreadQuantityFun] = useGetUnreadQuantityMutation()
  const [getDeliveryPersonFun] = useGetDeliveryPersonMutation()
  const [logoutFun] = useLogoutMutation()

  let p = useSelector(state => state.my.notice)
  let userData = useSelector(state => state.login.userInfo)
  
  useEffect(() => {
    useGetStorage('userInfo').then(res => {
      setUserInfo(res.userInfo)
      setProductList(res.productList)
    })
    getProductUsageCount()
    getDeliveryPerson()
  },[userData])

  useEffect(() => {
    getUnreadQuantity()
  },[p])

  //获取专属交付顾问
  const getDeliveryPerson = () => {
    getDeliveryPersonFun({}).then(res => {
      setDeliveryPerson(res.data?.result)
    })
  }

  //获取消息通知未读数量
  const getUnreadQuantity = () => {
    getUnreadQuantityFun({}).then(res => {
      setUnreadCount(res.data.result)
    })
  }

  //获取流量点数
  const getProductUsageCount = () => {
    getProductUsageCountFun({productUsageType:'SCORE'}).then(res => {
      setProductUsageData(res.data.result)
    })
  }

  //退出系统
  const handleExit = () => {
    logoutFun({}).then(res => {
      router.replace('/login')
    })
  }

  return (
    <PageScrollView bodyStyle={{paddingHorizontal: 0, gap: 0, backgroundColor: '#FFF'}}>
      <View style={{paddingHorizontal: 16}}>
        <View style={{marginTop: 10}}>
          <Flex justify='between'>
            <Flex>
              <Image style={{width: 48, height: 48, borderRadius: 48}} source={{uri: userInfo?.avatar}} resizeMode={'contain'}></Image>
              <View style={{marginLeft: 10}}>
                <Text style={{fontSize: 17}}>{userInfo?.realname}</Text>
                {
                  userInfo?.adminFlag ? 
                  <Text style={{color: 'rgba(0, 0, 0, 0.5)', fontSize: 12, marginTop: 5}}>管理员</Text>
                  : null
                }
                
              </View>
            </Flex>

            <TouchableOpacity style={{marginRight: 18}} onPress={() => router.push('/my/notice')}>
              <View style={{position: 'relative'}}>
                <Text style={{fontFamily: 'FcIconFont', fontSize: 25, color: '#000000'}}>&#xe677;</Text>
                {
                  unreadCount != 0 ?
                  <Text style={styles.message_box}>{unreadCount}</Text>
                  : null
                }
              </View>
            </TouchableOpacity>
          </Flex>
        </View>

        <LinearGradient 
          style={styles.system_box}
          colors={['#2856FF', '#BE46FF']}
          start={{x: 0, y: 0}}
          end={{x: 1, y: 1}}
        >
          {
            productList?.map((item:any, index:any) => (
              <Flex key={index} style={{marginBottom: 17}}>
                <Text style={{color: '#FFF'}}>
                  {item.productVersionCode.includes('MM') ? 'AI系统' : item.productVersionCode.includes('SCRM') ? 'AISCRM系统' : item.productVersionCode}
                  到期时间：{formatTimestamp(item.endDate, 'YYYY-MM-DD')}
                </Text>
                {
                  item.daysToExpire ? 
                  <Text style={styles.system_date}>剩余{item.daysToExpire}天</Text>
                  : null
                }
                
              </Flex>
            ))
          }

          <TouchableOpacity style={styles.deliver_box} onPress={() => setDeliveryPersonOpen(true)}>
            <LinearGradientText textName='联系专属交付顾问续费' colorList={['#2856FF', '#BE46FF']} fontSize={15}/>
          </TouchableOpacity>
        </LinearGradient>
      </View>
      
      <TouchableOpacity onPress={() => router.push('/my/usageRecord')}>
        <Flex style={styles.form_item} justify='between'>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 5}}>&#xe679;</Text>
            <Text style={styles.form_item_text}>AI流量费</Text>
          </Flex>
          <Flex>
            <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>剩余：<Text style={{color: '#2856FF'}}>{productUsageData?.usableUsage}</Text> 点数</Text>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)', marginLeft: 5}}>&#xe678;</Text>
          </Flex>
        </Flex>
      </TouchableOpacity>
      <View style={{height: 8, backgroundColor: '#f6f6f6', marginBottom: 8}}></View>

      <TouchableOpacity onPress={() => Linking.openURL('https://scnsrg19kpx2.feishu.cn/docx/Bl2ZdwL7Zo2KQfxluZCcTM4tnke')}>
        <Flex style={styles.form_item} justify='between'>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 5}}>&#xe62c;</Text>
            <Text style={styles.form_item_text}>帮助中心</Text>
          </Flex>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)', marginLeft: 5}}>&#xe678;</Text>
          </Flex>
        </Flex>
      </TouchableOpacity>

      <TouchableOpacity onPress={() => router.push('/my/feedback')}>
        <Flex style={styles.form_item} justify='between'>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 5}}>&#xe630;</Text>
            <Text style={styles.form_item_text}>意见反馈</Text>
          </Flex>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)', marginLeft: 5}}>&#xe678;</Text>
          </Flex>
        </Flex>
      </TouchableOpacity>
      <View style={{height: 8, backgroundColor: '#f6f6f6', marginBottom: 8}}></View>

      <TouchableOpacity onPress={() => router.push('/my/phone')}>
        <Flex style={styles.form_item} justify='between'>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 5}}>&#xe63b;</Text>
            <Text style={styles.form_item_text}>手机号</Text>
          </Flex>
          <Flex>
            <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>{userInfo?.phone || '未绑定'}</Text>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)', marginLeft: 5}}>&#xe678;</Text>
          </Flex>
        </Flex>
      </TouchableOpacity>

      <TouchableOpacity onPress={() => {}}>
        <Flex style={styles.form_item} justify='between'>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 5}}>&#xe615;</Text>
            <Text style={styles.form_item_text}>微信号</Text>
          </Flex>
          <Flex>
            <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>未绑定</Text>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)', marginLeft: 5}}>&#xe678;</Text>
          </Flex>
        </Flex>
      </TouchableOpacity>

      <TouchableOpacity onPress={() => router.push('/my/updatePassword')}>
        <Flex style={styles.form_item} justify='between'>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 5}}>&#xe636;</Text>
            <Text style={styles.form_item_text}>密码修改</Text>
          </Flex>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)', marginLeft: 5}}>&#xe678;</Text>
          </Flex>
        </Flex>
      </TouchableOpacity>
      <View style={{height: 8, backgroundColor: '#f6f6f6', marginBottom: 8}}></View>

      <TouchableOpacity onPress={() => router.push('/my/about')}>
        <Flex style={styles.form_item} justify='between'>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 18, color: '#000000', marginRight: 5}}>&#xeb65;</Text>
            <Text style={styles.form_item_text}>关于我们</Text>
          </Flex>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)', marginLeft: 5}}>&#xe678;</Text>
          </Flex>
        </Flex>
      </TouchableOpacity>

      <TouchableOpacity onPress={() => setNewVersionOpen(true)}>
        <Flex style={styles.form_item} justify='between'>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 5}}>&#xe640;</Text>
            <Text style={styles.form_item_text}>检查更新</Text>
          </Flex>
          <Flex>
            <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>1.0.0</Text>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)', marginLeft: 5}}>&#xe678;</Text>
          </Flex>
        </Flex>
      </TouchableOpacity>

      <TouchableOpacity onPress={() => {}}>
        <Flex style={styles.form_item} justify='between'>
          <Flex>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#000000', marginRight: 5}}>&#xe6c7;</Text>
            <Text style={styles.form_item_text}>清除缓存</Text>
          </Flex>
          <Flex>
            <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>271.5M</Text>
            <Text style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'rgba(0, 0, 0, 0.5)', marginLeft: 5}}>&#xe678;</Text>
          </Flex>
        </Flex>
      </TouchableOpacity>

      <TouchableOpacity onPress={() => setExitOpen(true)}>
        <Flex style={styles.exit_box} justify='center'>
          <Text style={{fontFamily: 'FcIconFont', fontSize: 20, color: '#FA5151', marginRight: 5}}>&#xe698;</Text>
          <Text style={{fontSize: 15, color: '#FA5151'}}>退出系统</Text>
        </Flex>
      </TouchableOpacity>
      
      {/* 版本更新弹窗 */}
      <FcModal
        isOpen={newVersionOpen}
        transparent
        closeShow={true}
        animationType='fade'
        onFcModalClose={() => setNewVersionOpen(false)}
        style={{width: '80%', borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
        titleBottomBorderWidth={0}
        titleText={'发现新版本'}
        bottom={
          <TouchableOpacity onPress={() => handleWxPay()}>
            <Flex justify='center'>
              <FcButton
                type='BjJB'
                colors={['#6989FF', '#C65EFD']}
                style={{width: '60%', height: 40, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 15}}
                textName='立即更新'
              />
            </Flex>
          </TouchableOpacity>
        }
      >
        <View style={{marginBottom: 20}}>
          <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}># [软件名称]新版本发布内容 亲爱的用户们，我们很高兴地宣布，[软件名称]迎来了一次重要的版本更新，新版本号为[X]。本次更新为大家带来了一系列丰富且实用的功能优化与改进，致力于为您提供更优质、高效、便捷的使用体验。 ## 一、新增功能 1. **智能推荐引擎升级**：全新的智能推荐算法上线，能够根据您的使用习惯、历史记录</Text>
        </View>
      </FcModal>

      <FcModal
        isOpen={deliveryPersonOpen}
        transparent
        closeShow={true}
        animationType='fade'
        onFcModalClose={() => setDeliveryPersonOpen(false)}
        style={{width: 350, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
        titleBottomBorderWidth={0}
      >
        {
          deliveryPerson ? 
          <Flex direction='column'>
            <Image style={{width: '100%', height: 160}} source={{uri: deliveryPerson.avatar}} resizeMode={'contain'}></Image>
            <Text style={{fontWeight: 'bold', marginVertical: 10}}>专属交付顾问：{deliveryPerson.name}</Text>
            <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>{deliveryPerson.description}</Text>
            <View style={styles.qrcode}>
              <Image style={{width: '100%', height: '100%'}} source={{uri: deliveryPerson.qrCode}} resizeMode={'cover'}></Image>
            </View>
            <Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>长按保存二维码，添加企微专属交付顾问</Text>
            <Flex style={{marginTop: 30, marginBottom: 10}}>
              <Text style={{fontFamily: 'FcIconFont', fontSize: 22, color: '#000000', marginRight: 5}}>&#xe63b;</Text>
              <Text>电话联系：<Text style={{color: '#2856FF'}}>{deliveryPerson.phone}</Text></Text>
            </Flex>
            <Text><Text style={{color: 'rgba(0, 0, 0, 0.5)'}}>工作时间：</Text>工作日 09:00 - 18:30</Text>
          </Flex>
          :
          <Flex><NoData hintText='暂无专属交付顾问'/></Flex>
        }
      </FcModal>

      {/* 退出系统弹窗 */}
      <FcModal
        isOpen={exitOpen}
        transparent
        closeShow={false}
        animationType='fade'
        onFcModalClose={() => setExitOpen(false)}
        style={{width: 280, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
        titleText={'温馨提醒'}
        titleBottomBorderWidth={0}
        footer={[
          {
            text: '取消',
            onPress: () => setExitOpen(false),
            style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
          },
          {
            text: '确认',
            onPress: () => handleExit(),
            style: { color: '#2856FF',fontSize: 17 },
          },
        ]}
      >
        <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>是否确认退出系统</Text>
      </FcModal>
    </PageScrollView>
  )
}

export default my

const styles = StyleSheet.create({
  message_box: {
    position: 'absolute',
    top: -10,
    right: -10,
    width: 18,
    height: 18,
    fontSize: 12,
    color: '#FFF',
    textAlign: 'center',
    borderRadius: 18,
    backgroundColor: '#FA5151',
  },
  system_box: {
    paddingHorizontal: 15,
    paddingVertical: 20,
    borderRadius: 8,
    backgroundColor: '',
    marginTop: 15,
  },
  system_date: {
    height: 18,
    lineHeight: 18,
    fontSize: 10,
    borderRadius: 3,
    color: '#FF484A',
    marginLeft: 10,
    paddingHorizontal: 6,
    backgroundColor: 'rgba(255, 255, 255, 0.9)'
  },
  deliver_box: {
    height: 44,
    borderRadius: 8,
    backgroundColor: 'rgba(255, 255, 255, 0.9)',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  form_item: {
    width: '100%',
    height: 56,
    paddingHorizontal: 16,
  },
  form_item_text: {
    fontSize: 15,
    color: 'rgba(0, 0, 0, 0.9)',
  },
  exit_box: {
    height: 56,
    borderRadius: 8,
    marginTop: 16,
    marginHorizontal: 16,
    backgroundColor: 'rgba(250, 81, 81, 0.1)',
  },
  qrcode: {
    width: 120,
    height: 120,
    borderRadius: 8,
    backgroundColor: '#FFF',
    overflow: 'hidden',
    marginVertical: 10,
  },
})

